﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;

namespace nwrole.Module.lib
{
    public class ModuleDebug : IModuleDebug
    {
        private List<IModuleLogger> _moduleLoggers = new List<IModuleLogger>();

        private int _superModulePort;
        private string _serviceName;

        public ModuleDebug(int superModulePort, string serviceName)
        {
            ThreadTraceListener listen = new ThreadTraceListener();
            listen.OnTrace += OnThreadTraceMsg;

            Trace.Listeners.Add(listen);

            _superModulePort = superModulePort;
            _serviceName = serviceName;
        }

        public void Pulse(string message)
        {
            try
            {
                using (WebClient client = new WebClient())
                {
                    byte[] response = client.UploadValues("http://localhost:" + _superModulePort + "/api/Pulse", new NameValueCollection()
                   {
                       { "ServiceName", _serviceName },
                       { "Message", message }
                   });
                }
            }
            catch
            {
            }
        }

        public void RegisterLogger(IModuleLogger logger)
        {
            _moduleLoggers.Add(logger);
        }

        public void UnregisterLogger(IModuleLogger logger)
        {
            _moduleLoggers.Remove(logger);
        }

        private void OnThreadTraceMsg(object sender, ThreadTraceEventArgs args)
        {
            //PluginWrapper wrapper = pluginWrappers.SingleOrDefault(w => w.Thread != null && w.Thread.ManagedThreadId.ToString().Equals(args.EventCache.ThreadId));

            LogLevel logLevel;
            switch (args.EventType)
            {
                case TraceEventType.Critical:
                    logLevel = LogLevel.Critical;
                    break;
                case TraceEventType.Error:
                    logLevel = LogLevel.Error;
                    break;
                case TraceEventType.Warning:
                    logLevel = LogLevel.Warning;
                    break;
                case TraceEventType.Information:
                case TraceEventType.Verbose:
                    logLevel = LogLevel.Info;
                    break;
                default:
                    logLevel = LogLevel.Info;
                    break;
            }

            /*if (wrapper != null)
                Log(NwroleObjectType.Plugin, wrapper.PluginData.Id, logLevel, wrapper.PluginData.DisplayName + ": " + args.Message, null);
            else
                Log(NwroleObjectType.Service, ServiceId, logLevel, args.Message, null);*/

            foreach(var logger in _moduleLoggers)
                logger.Log(logLevel, args.Message);
        }
    }
}
